const path = require('path')

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'

// ele按需加载
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

// jsx支持
import vueJsx from '@vitejs/plugin-vue-jsx'

// gzip
import viteCompression from 'vite-plugin-compression'

// eslint
import EslintPlugin from 'vite-plugin-eslint'

// https://vitejs.dev/config/
export default (({ mode, command }) => {

  // 获取环境变量
  function getViteVariable(key) {
    return loadEnv(mode, process.cwd())[key]
  }

  let config = {
    // 打包路径，根据不同的环境变量切换
    base: getViteVariable('VITE_BASE_URL') || './',

    // 插件
    plugins: [
      vue(),
      vueJsx(),

      // 按需加载ele
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),

      // gzip
      viteCompression(),

      // eslint
      EslintPlugin({
        exclude: ['./node_modules/**', './src/utils/tools.js', './src/api/http.js']
      })
    ],

    // css
    css: {
      // css预处理器
      preprocessorOptions: {
        less: {
          charset: false,
          // additionalData: '@import "./src/assets/css/base.less";',
        },
      },
    },

    // 构建
    build: {
      // 输出文件夹
      outDir: 'dist',

      // 是否生成map文件
      sourcemap: true,

      terserOptions: {
        compress: {
          keep_infinity: true,
          // warnings: false,
          drop_console: true,  // 打包时删除console
          drop_debugger: true, // 打包时删除 debugger
          pure_funcs: ['console.log'],
        },
        output: {
          // 去掉注释内容
          comments: true,
        },
      },

      rollupOptions: {
        output: {
          manualChunks: {
            // 拆分代码，这个就是分包，配置完后自动按需加载
            vue: ['vue', 'vue-router', 'pinia'],
            element: ['element-plus']
          },
        },
      },
    },

    // 解析配置
    resolve: {
      alias: {
        '@': path.join(__dirname, './src'),
        '@c': path.join(__dirname, './src/components'),
        '@u': path.join(__dirname, './src/utils'),
      },
    },

    // 服务
    server: {
      host: getViteVariable('VITE_HOST'),
      port: getViteVariable('VITE_PORT'),
      open: false,
      hmr: {
        overlay: false
      },
      proxy: {
        '/auth': {
          target: 'https://console-mock.apipost.cn/app/mock/project/ebf1e521-00ad-4782-9819-8c8ffa30035b', // 所要代理的目标地址
          changeOrigin: true,
          rewrite: path => path.replace(/^\/auth/, '/auth')
        }
      }
    }
  }

  return defineConfig(config)
})
